package org.hikari.qqbot.xiuxian.task.impl;

import cn.hutool.core.date.DateUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.hikari.qqbot.xiuxian.command.ICommand;
import org.hikari.qqbot.xiuxian.command.standard.yaoyuan.ShouHuoCommand;
import org.hikari.qqbot.xiuxian.command.standard.yaoyuan.YaoYuanCommand;
import org.hikari.qqbot.xiuxian.command.standard.yaoyuan.YiJianZhongZhiCommand;
import org.hikari.qqbot.xiuxian.service.bo.UserSetting;
import org.hikari.qqbot.xiuxian.task.TaskParams;
import org.hikari.qqbot.xiuxian.task.TypedITask;
import org.hikari.qqbot.xiuxian.task.UserTaskRuntime;
import org.hikari.qqbot.xiuxian.util.MessageUtil;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * created at 2024-12-23 23:16:23
 *
 * @author yinchao
 * @version 1.0
 **/
@Slf4j
@Component
public class YaoYuanTask extends TypedITask<YaoYuanTask.Config> {

    @Override
    public String getId() {
        return "药园";
    }

    @Override
    public Collection<ICommand> process(UserTaskRuntime runtime, String message) {
        UserSetting setting = runtime.getUserSetting();
        YaoYuanTask.Config config = config(setting);

        // 药园命令的结果
        if (message.contains("目前药园种植情况如下")) {
            List<String> matched = MessageUtil.matchAllPattern(message, "区域[0-9]+：\\(([\\u4e00-\\u9fa5]+)\\)\\(([0-9]+分钟|已)成熟\\)", 2);
            if (matched.isEmpty()) {
                return List.of(buildYiJianZhongZhiCommandAutoSeed(runtime, config));
            } else {
                boolean hasCompleted = false;
                int minMinutes = Integer.MAX_VALUE;
                int maxMinutes = Integer.MIN_VALUE;
                for (String s : matched) {
                    if (s.equals("已")) {
                        hasCompleted = true;
                    } else {
                        int remainingMinutes = Integer.parseInt(s.substring(0, s.length() - 2));
                        minMinutes = Math.min(minMinutes, remainingMinutes);
                        maxMinutes = Math.max(maxMinutes, remainingMinutes);
                    }
                }
                // 全都都是已成熟,  那么直接发送
                if (maxMinutes == Integer.MIN_VALUE || minMinutes == Integer.MAX_VALUE) {
                    return List.of(new ShouHuoCommand());
                }
                // 等待所有成熟
                if (config.isWaitAllCompleted()) {
                    return List.of(new ShouHuoCommand().delay(DateUtil.offsetMinute(new Date(), maxMinutes)));
                } else {
                    if (hasCompleted) {
                        return List.of(new ShouHuoCommand());
                    }
                    return List.of(new ShouHuoCommand().delay(DateUtil.offsetMinute(new Date(), minMinutes)));
                }
            }
        }


        if (message.contains("区域") && MessageUtil.matchFirstPattern(message, "区域[0-9]+：[\\u4e00-\\u9fa5]+[+]\\([0-9]+×[0-9]+\\)") != null) {
            ICommand command = buildYiJianZhongZhiCommandAutoSeed(runtime, config);
            return List.of(command);
        }

        if (message.contains("一键种植成功！")) {
            String timeStr = MessageUtil.matchFirstPattern(message, "预计成熟：([0-9]+-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+)", 1);
            if (timeStr != null) {
                Date data = DateUtil.parseDateTime(timeStr);
                return List.of(new ShouHuoCommand().delay(data));
            }
        }

        if (message.contains("请先购买种子！")) {
            String part = MessageUtil.matchFirstPattern(message, "你还没有([\\u4e00-\\u9fa5]+种子)，请先购买种子！", 1);
            ICommand command;
            if (part == null) {
                command = buildYiJianZhongZhiCommandAutoSeed(runtime, config);
            } else {
                String selectedSeed = config.getSeedNames().stream()
                        .filter(s -> !Objects.equals(part, s))
                        .findFirst()
                        .orElse(null);
                if (selectedSeed == null) {
                    log.info("[{} - {}] 没有种子可以种, 延迟发送种植命令", setting.getUserId(), getId());
                    command = buildYiJianZhongZhiCommandAutoSeed(runtime, config).delay(1000L * 60 * 10);
                } else {
                    command = buildYiJianZhongZhiCommandBySeedName(runtime, config, selectedSeed);
                }
            }
            return List.of(command);
        }

//        if (message.contains("种子如下：")) {
//            List<String> parts = MessageUtil.matchAllPattern(message, "([\\u4e00-\\u9fa5]+种子)\\([0-9]+\\)");
//            if (!parts.isEmpty()) {
//                Collection<String> duplicatedParts = new LinkedHashSet<>(parts);
//                Map<String, Integer> seedNumMap = new LinkedHashMap<>();
//                for (String part : duplicatedParts) {
//                    try {
//                        int begin = part.indexOf("(");
//                        int end = part.indexOf(")");
//                        String seedName = part.substring(0, begin);
//                        String seedNumStr = part.substring(begin + 1, end);
//                        int seedNum = Integer.parseInt(seedNumStr);
//                        if (seedNum > 0) {
//                            seedNumMap.put(seedName, seedNum);
//                        }
//                    } catch (RuntimeException e) {
//                        log.error("[{} - {}] 卖种子命令回复文本片段解析失败！片段 = {}", setting.getUserId(), getId(), part, e);
//                    }
//                }
//                log.info("[{} - {}] 解析目前种子情况如下: {}", setting.getUserId(), getId(), seedNumMap);
//            }
//        }

        return null;
    }

    private static ICommand buildYiJianZhongZhiCommandAutoSeed(UserTaskRuntime runtime, Config config) {
        Integer seedIndex = runtime.getMeta().get(TaskParams.yaoYuanSeedIndex);
        if (seedIndex == null) {
            seedIndex = 0;
        }
        seedIndex = seedIndex % config.getSeedNames().size();
        runtime.getMeta().set(TaskParams.yaoYuanSeedIndex, seedIndex + 1);
        String seedName = config.getSeedNames().get(seedIndex);
        return new YiJianZhongZhiCommand(seedName).times(config.getPlantTimes());
    }

    private static ICommand buildYiJianZhongZhiCommandBySeedName(UserTaskRuntime runtime, Config config, String seedName) {
        updateSeedIndexByName(runtime, config, seedName);
        return new YiJianZhongZhiCommand(seedName).times(config.getPlantTimes());
    }

    private static void updateSeedIndexByName(UserTaskRuntime runtime, Config config, String seedName) {
        int i = 0;
        for (String seed : config.seedNames) {
            if (Objects.equals(seedName, seed)) {
                break;
            }
            i++;
        }
        runtime.getMeta().set(TaskParams.yaoYuanSeedIndex, i + 1);
    }

    @Override
    public ICommand initCommand(UserSetting setting) {
        return new YaoYuanCommand();
    }

    @Getter
    @Setter
    public static class Config {

        /**
         * 种植的种子名称
         */
        private List<String> seedNames;
        /**
         * 等待所有种子成熟
         */
        private boolean waitAllCompleted = true;
        /**
         * 种植次数
         */
        private int plantTimes = 10;

    }

}
